function [] = latexRegTable( table, filename, title, label, footnote)
% Create LaTeX table from MATLAB table containing arbitrary strings
% 
%
% INPUTS
%       table: MATLAB table object
%       filename: Path to print to file
%       title: Title of the table
%       label: Label for LaTex identification
%       footnote: Table notes
%       num_discrete: Number of discrete statistics
%
%

% Table metadata
numDataRows = size(table,1);
numDataCols = size(table,2);

%colHeaders = table.Properties.VariableDescriptions;
colHeaders = table.Properties.VariableNames;
rowNames = table.Properties.RowNames;

% Formatting
formats = ['%15s',repmat('\t%s',1,numDataCols)];
formats = regexprep(formats,'\\t','&');

label = sprintf('\\label{tab:%s}',label);

% Open table file
fid = fopen(filename, 'w');

% Frontmatter
fprintf(fid, '\\begin{table}[ht]\n');
fprintf(fid, '\t\\centering\n');
fprintf(fid, '\t\t\\caption{%s%s}\n',title,label);
fprintf(fid, '\t\t\t\\begin{tabular}{%s}\n', ['l' repmat('c',1,numDataCols) ]);

% Toprule
fprintf(fid, '\t\t\t\t\\toprule\n');

% Column headers
fprintf(fid, repmat('\t',1,5));
for i = 1:numDataCols
    fprintf(fid, '&');
    fprintf(fid, '\\multicolumn{1}{c}{%s}', colHeaders{i});
    
    if i == numDataCols
        fprintf(fid, '\\\\\n');
    end
end

% Column numbers 
fprintf(fid, repmat('\t',1,5));
for i = 1:numDataCols
    fprintf(fid, '&');
    fprintf(fid, '\\multicolumn{1}{c}{(%d)}', i);
    
    if i == numDataCols
        fprintf(fid, '\\\\\n');
    end
end

% Midrule
fprintf(fid, '\t\t\t\t\t\\midrule\n');


% Round data columns
%for i = 1:numDataCols
   % sprintf(' %.4f\n',table.(i));
   % format short g;table
%end

% Write data rows
for i = 1:numDataRows
    fprintf(fid, ['\t\t\t\t\t' formats '\\\\\n'], rowNames{i}, table{i,:});
    %fprintf(fid, ['\t\t\t\t\t' formats '\\\\\n'], rowNames{i}, roundn(table{i,:}, -3));
    %fprintf(fid, ['\t\t\t\t\t' formats '\\\\\n'], rowNames{i}, sprintf(' %.4f\n',table.(i)));
    %fprintf(fid, ['\t\t\t\t\t' formats '\\\\\n'], rowNames{i}, num2str(roundn(table{i,:}, -4)));
end




% Footer
fprintf(fid, '\t\t\t\t\t\\bottomrule\n');
fprintf(fid, '\t\t\t\t\t\\multicolumn{%d}{p{%4.2f\\hsize}}{\\footnotesize %s}\n',...
    numDataCols + 1, 0.9, footnote);

fprintf(fid, '\t\t\t\\end{tabular}\n');
fprintf(fid, '\\end{table}');
fprintf(1,'Written summary statistics table to %s\n', filename);

end